#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#define READTP_BUFSIZ  32768
register unsigned long tpreg __asm__("tp");

int main(int argc, char *argv[])
{
	int fd;
	long pid;
	char maps[128], * pbuf;

	fd = -1;
	pbuf = NULL;
	pid = (long) getpid();

	fprintf(stdout, "tp register for process %ld: 0x%lx\n", pid, tpreg);
	fflush(stdout);

	snprintf(maps, sizeof(maps), "/proc/%ld/maps", pid);
	nice(0);
	pbuf = (char *) calloc(0x1, READTP_BUFSIZ);
	if (pbuf == NULL) {
		fputs("Error, system out of memory!\n", stderr);
		fflush(stderr);
		return 1;
	}

	fd = open(maps, O_RDONLY | O_CLOEXEC, 0644);
	if (fd == -1) {
		int error = errno;
		fprintf(stderr, "Error, failed to open(%s): %s\n", maps, strerror(error));
		fflush(stderr);
		free(pbuf);
		return 2;
	}

	for (;;) {
		ssize_t rl1;
		rl1 = read(fd, pbuf, READTP_BUFSIZ);
		if (rl1 <= 0)
			break;
		if (write(0x1, pbuf, (size_t) rl1) != rl1) {
			int error = errno;
			fprintf(stderr, "Error, failed to write stdout: %s\n", strerror(error));
			fflush(stderr);
		}
	}

	close(fd);
	free(pbuf);
	return nice(0);
}
